package ink.durian.web;

import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟第三方软件的首页
 *
 * @author: Durian
 * @date: 2021-10-20 21:13
 */
@Controller
@RequestMapping("/index")
public class IndexController {

    @Value("${oauth.codeUrl}")
    public String codeUrl;
    @Value("${oauth.appId}")
    public String appId;
    @Value("${oauth.secret}")
    public String secret;
    @Value("${oauth.authUrl}")
    public String authUrl;
    @Value("${oauth.refreshUrl}")
    public String refreshUrl;

    @GetMapping
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        if (true) {
            // 查询令牌有效性，无效则重定向到授权服务
            mv.setViewName("redirect:"+ codeUrl);
            return mv;
        }
        // 使用令牌访问数据

        mv.setViewName("index");
        mv.addObject("data", "Durian");
        return mv;
    }

    // 回调接口
    @GetMapping("/authRecall")
    public String page(HttpServletRequest request) {
        // 获取授权服务提供的 授权码 code
        String code = request.getParameter("code");
        System.out.println("code = " + code);
        // 使用 授权码 获取令牌
        Map<String, Object> params = new HashMap<>();
        params.put("appId", appId);
        params.put("secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String post = HttpUtil.post(authUrl, params);
        System.out.println("post = " + post);
        // 需要 appId  secret
        // 发送post
        // 返回accessToken
        // 返回首页
        return "index";
    }

    @GetMapping("/refresh")
    @ResponseBody
    public String refresh(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        params.put("appId", appId);
        params.put("refresh_token", request.getParameter("refresh_token"));
        params.put("grant_type", "refresh_token");
        String post = HttpUtil.post(refreshUrl, params);
        System.out.println("post = " + post);
        return post;
    }
}
